//
//  AppDelegate.m
//  SEGUhomeChassis
//
//  Created by 山刘 on 2019/4/15.
//  Copyright © 2019年 山刘. All rights reserved.
//

#import "AppDelegate.h"
#import <Commom/SEGScreenSupportRotateDelegate.h>
#import <commonThirds/QYCrashProtector.h>
#import <Commom/SEGSecurityManager.h>
#import <CommonMediator/SEGUhomeMediatorConfig.h>
#import <Commom/SEGCommonConfig.h>
#import "SEGOldLoginViewController.h"
#import <Commom/SEGProtectCode.h>
#import <Commom/SEGSecurityManager.h>
#import "SEGSplashAdvertController.h"
#import <SEGPlatform/SEGWaitingViewController.h>
#import <GDTMobSDK/GDTSDKConfig.h>
#import "SEGThirdConfigManager.h"
@interface AppDelegate () <SEGScreenSupportRotateDelegate,WXApiDelegate>
@property (nonatomic, assign) NSInteger enterBackgroundTimeStamp;
@end

@implementation AppDelegate

@synthesize isForceLandscape;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    #ifdef DEBUG
        [SEGCommonConfig shared].isAllowNetworkProxy = YES;
    #else
        // 安全1.[等保改造]防止重签名&禁止动态调试 若有则直接退出程序
        [SEGProtectCode seg_jianchaSignForProtectWithCodeSignId:@"W46L3E496A" andBundleID:@"com.segi.uhome"];
        [SEGProtectCode seg_ptrace];
        [SEGProtectCode seg_checkSysctlDebugger];
    
        [QYCrashProtector qy_openAllCrashProtector];
        // 安全4.是否允许抓包
        [SEGCommonConfig shared].isAllowNetworkProxy = NO;
    #endif
    
    // 自定义登录注册页面 (v4.9.2)
    [SEGUhomeMediatorConfig shared].initLoginVCBlock = ^UIViewController *(NSDictionary *info) {
        SEGOldLoginViewController *login = [[SEGOldLoginViewController alloc] init];
        login.messageDesc = info;
        return login;
    };
    
    // 安全2.检测到动态注入，直接退出
    if ([SEGSecurityManager shared].isDynamicInjection) {
        UIAlertController *alterController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"检测到设备已越狱或被动态注入，存在安全风险" preferredStyle:UIAlertControllerStyleAlert];
        [alterController addAction:[UIAlertAction actionWithTitle:@"退出程序" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            exit(1);
        }]];

        [self segInitRootWindow:nil];
        [self.window.rootViewController presentViewController:alterController animated:YES completion:nil];
        return YES;
    }
    
    // 安全3.检测到越狱，不退出只提示
    // [4.9.9需求]
    BOOL isJailBreak = [[SEGSecurityManager shared] isJailBreak];
    if (isJailBreak) {
        UIAlertController *alterController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"检测到设备已被越狱，存在安全风险" preferredStyle:UIAlertControllerStyleAlert];
        [alterController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            // 初始化界面
            [self seg_initialAppWithOptions:launchOptions];
        }]];
        
        [self segInitRootWindow:nil];
        [self.window.rootViewController presentViewController:alterController animated:YES completion:nil];
        return YES;
    }
    
    [self seg_initialAppWithOptions:launchOptions];
    return YES;
}

// 初始化app
- (void)seg_initialAppWithOptions:(NSDictionary *)launchOptions {
    // 安全4.是否允许抓包（上线的时候需要关闭）
    [SEGCommonConfig shared].isAllowNetworkProxy = YES;
    
    // 1.设置项目入口
    [self segInitRootWindow:[SEGSplashAdvertController new]];
    
    // 首页启动广告
    [[NSUserDefaults standardUserDefaults] setObject:@(NO) forKey:kUserDefaultLaunchAdvertisement];
    
    // 2.设置项目环境
    [[NSUserDefaults standardUserDefaults] setObject:UserDefaultsClientServerValue_beta forKey:UserDefaultsClientServerKey];
    [[NSUserDefaults standardUserDefaults] setObject:UserDefaultsBrowerServerValue_beta forKey:UserDefaultsBrowerServerKey];
    [[NSUserDefaults standardUserDefaults] setObject:@"64" forKey:UserDefaultsClientVersionCodeTypeKey];
    [[NSUserDefaults standardUserDefaults] setObject:@(NO) forKey:kUserDefaultIsProduction];//是否为生产环境（上架或打AdHoc包时必须改为YES）
    
    // 3.初始化第三方Key值
    [self segInitThirdSDK];
    
    //4.安全政策版本号
    [SEGSecurityManager shared].securityVersion = 4;
    
    // 设置请求header
    [SEGHTTPBusinessManager seg_serRequestHeaderDictionary:@{
                                                             @"systemVersionCode":[UIDevice currentDevice].systemVersion,
                                                             @"phoneModel": [[UIDevice currentDevice]machineModelName],
                                                             @"version":[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"],
                                                             @"communityId":kAccountCommunityID,
                                                             @"source":kSource,
                                                             @"platform":kCompanyPlatformCode,
                                                             @"clientType":kAppPlatformCode,
                                                             @"deviceId": [SEGCKeyChainStore stringWithUUIDStringInKeyChainStore],
                                                             @"versionCode":[[NSUserDefaults standardUserDefaults] valueForKey:UserDefaultsClientVersionCodeTypeKey]
                                                             }];
    
    //初始化极光推送
    [[SEGUhomeMediator sharedInstance] seg_initJpushWithOptions:launchOptions];
    
    // 初始化界面
    //[[SEGUhomeMediator sharedInstance] seg_compareVersionAndPush:@{}];
}

/// 设置项目入口
/// @param vc root VC
-(void)segInitRootWindow:(UIViewController*)vc {
    UIViewController *root = vc ? vc : [[SEGUhomeMediator sharedInstance] seg_initWaitingViewController:@{}];
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = kColor_W;
    self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:root];
    [self.window makeKeyAndVisible];
}

/**
 * 初始化第三方SDK的app ID
 * @author Sam
 */
-(void)segInitThirdSDK{
    [[SEGThirdConfigManager sharedInstance] segInitThirdSDK];
    
    [[SEGUhomeMediator sharedInstance] seg_startAnalytics:@{}]; //开启四格埋点统计
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeNative];
    [SVProgressHUD setBackgroundLayerColor:[kColor_W colorWithAlphaComponent:0.2]];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeCustom];
    
    // 腾讯广点通
    [GDTSDKConfig enableGPS:YES]; // 获取用户的GPS信息，默认值为NO -> 以便获取定向广告
    [GDTSDKConfig setChannel:14]; // 设置渠道号 -> 协助平台提升流量变现
    [GDTSDKConfig registerAppId:kGDTAppkey];
}

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
    /// Required - 注册 DeviceToken
    [[SEGUhomeMediator sharedInstance]seg_initForDidRegisterForRemoteNotificationsWithDeviceToken:@{@"deviceToken":deviceToken}];
}

- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler {
    return [WXApi handleOpenUniversalLink:userActivity delegate:[SEGThirdConfigManager sharedInstance]];
}

//接受到推送 都会调用
- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
    [[SEGUhomeMediator sharedInstance]seg_initForDidReceiveRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

//老的接受推送调用的方法，防止后台修改推送参数后收不到
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [[SEGUhomeMediator sharedInstance]seg_initForDidReceiveRemoteNotification:userInfo];
}

#pragma mark - APP Soft Boot
- (void)applicationDidEnterBackground:(UIApplication *)application{
    NSLog(@"%s",__FUNCTION__);
    self.enterBackgroundTimeStamp = [[NSDate date] timeIntervalSince1970];
}
- (void)applicationWillEnterForeground:(UIApplication *)application{
    NSLog(@"%s",__FUNCTION__);
    [self launchTencentAd];
}
#pragma mark - For Tencent Launch AD

/// load tentcent ad
-(void)launchTencentAd{
    NSInteger timeDif = [[NSDate date] timeIntervalSince1970] - self.enterBackgroundTimeStamp;// 前台退到后台的时间差-秒
    NSInteger interval = [self getTencentAdIntervalTime];// 后台设置加载腾讯广告的时间间隔
    
    if (interval > 0 && timeDif > interval) {
        NSLog(@"Launch Tencent AD!");
        SEGSplashAdvertController *VC = [SEGSplashAdvertController new];
        VC.isSoftBoot = YES;
        [[[SEGUhomeMediator sharedInstance] seg_getCurrentController:nil].navigationController pushViewController:VC animated:NO];
    }else{
        NSLog(@"Do not Launch Tencent AD!");
    }
}

/// <=0 不计时&不启动计时器
-(NSInteger)getTencentAdIntervalTime{
    // Value -> nil or "", Do not launch tencent ad when app soft boot.
    NSString* intervalTime = [[NSUserDefaults standardUserDefaults] valueForKey:@"TencentLaunchAdIntervalTimeKey"];
    if(intervalTime && [intervalTime isKindOfClass:[NSString class]] && [intervalTime length] > 0){
        return [intervalTime integerValue];
    }
    return 0;
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
    return [[SEGThirdConfigManager sharedInstance] dealWithOpenUrl:url];
}




@end
